<template>
  <div class="webchat_chat_info">
    <div class="tabsBar clearfix">
      <button class="prev" v-show="needOffset" @click="handlePrevBtnCLick">
        <i class="el-icon-arrow-left"></i>
      </button>
      <div class="tabswrapper" :style="{
        width: tabswrapperWidth + 'px'
      }">
        <ol class="tabs clearfix" :style="{
          transform: needOffset ? 'translateX(-' + offsetX + 'px)' : 'translateX(0px)'
        }">
          <SizeSync
            v-for="(tab, i) in tabs"
            :key="i"
            :size.sync="tab.size"
            tag="li"
            class="tab"
            :class="{
              active: activeName === tab.tabName || activeName === tab._id
            }"
            v-if="showTabs(tab.tabName)"
            @click.native="handleTab(tab)"
          >{{$t(tab.name) || tab.name}}
            <i class="icon-duijie iconfont" style="line-height: 12px;margin-left: 6px" v-if="!tab.type && !tab.editable"  @click.stop="openTabUrl(tab)"></i>
          </SizeSync>
          <li class="tab" style="width:1000px;"></li>
        </ol>
      </div>
      <button class="next" v-show="needOffset" @click="handleNextBtnCLick">
        <i class="el-icon-arrow-right"></i>
      </button>
      <button class="config" @click="handleEditTab">
        <i class="iconfont icon-peizhi"></i>
      </button>
    </div>
    <div class="tabPanels" :class="{tabPanelsScroll: activeName !== 'quickReply' || quickReplyView === 'selectView'}">
      <div class="tab" v-if="loadedList.has('customerInfo')" v-show="activeName === 'customerInfo'" >        
        <CustomerInformation
          :currentBusinessObj="currentBusinessObj"
          :webchatData="webchatData"
          :chatInfo="chatInfo"
          :customer="customer"
        ></CustomerInformation>
      </div>
      <div class="tabPanel" v-if="loadedList.has('shopping')" v-show="activeName === 'shopping'" >
        <showShopping :chatInfo="chatInfo"></showShopping>
      </div>
      <div class="tabPanel" v-if="loadedList.has('quickReply') && quickReplyView === 'selectView'" v-show="activeName === 'quickReply'" >
        <webchatQuickReply></webchatQuickReply>
      </div>
      <div class="tabPanel" v-if="loadedList.has('quickReply') && quickReplyView === 'listView'" v-show="activeName === 'quickReply'" >
        <webchatQuickReplyOld></webchatQuickReplyOld>
      </div>
      <div class="tabPanel" v-if="loadedList.has('auxiliaryAgent')" v-show="activeName === 'auxiliaryAgent'" >
        <auxilAgent></auxilAgent>
      </div>
      <div class="tabPanel" v-if="loadedList.has('business')" v-show="activeName === 'business'" >
        <div class="no-customer" v-if="!customer._id">
          <guide
            v-if="!customer._id"
            :isDailog="true"
            :customer="customer"
            :custType="custType"
            :currentBusinessObj="currentBusinessObj"
            :webchatData="webchatData"
            @addCustomer="addCustomer"
            @merged="mergeCustomer"
          ></guide>
        </div>
        <business class="business-webchat"
                  v-show="customer._id"
                  :busId="busId" :cid="customer._id"
                  link="webchat"
                  :reload="businessReload"
                  :custInfo="customer"
                  :showHistoryTable="false"
                  @event="businessEvent"
                  :refresh="firstIn"
                  :businessNumbers="webchatData.businessNumbers"
                  :cacheId="webchatData._id"></business>
      </div>
      <div class="tabPanel" v-for="tabUrl in tabUrls" v-if="tabUrl.click" v-show="activeName === tabUrl._id">
        <div class="iframe-wrap" :style="{height: tabUrl.businesses && tabUrl.businesses.length ? 'calc(100vh - 172)' : 'calc(100vh - 96px)'}">
          <div v-if="tabUrl.businesses && tabUrl.businesses.length > 0 && (!$store.state.session.account.tokenCheck || ($store.state.session.account.tokenCheck && token))" style="height:calc(100vh - 172px)">
            <div clss="businessesSelect" style="margin: 10px">业务类型</div>
            <el-select v-model="toolBarValue" filterable placeholder="请选择" style="margin: 0px 10px 10px">
              <el-option
                v-for="(toolBarItem, index) in tabUrl.businesses"
                :key="index"
                :label="toolBarItem.name"
                :value="toolBarItem.url">
              </el-option>
            </el-select>
            <iframe v-if="toolBarValue !== ''" :src="newUrl(toolBarValue)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
          </div>
          <iframe v-else-if="!$store.state.session.account.tokenCheck || ($store.state.session.account.tokenCheck && token)" :src="newUrl(tabUrl.url, tabUrl.isEncode)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
        </div>
      </div>
      <div class="toggleIcon" @click="handleToggleLayout" v-show="activeName !== 'business' && activeName !== 'customerInfo' && activeName !== 'quickReply' && activeName !== 'auxiliaryAgent' && activeName !== 'shopping'">
        <i class="iconfont icon-youjiantou" v-show="toggleLayoutOpen === true"></i>
        <i class="iconfont icon-zuojiantou" v-show="toggleLayoutOpen === false"></i>
      </div>
    </div>
    <edit-tab :tabs="tabs" ref="editTabIndex" @updateTabConfig="updateTabConfig"></edit-tab>
    <resize-sensor @resize="resize"/>
  </div>
</template>
<script type="text/javascript">
import { isEmpty } from 'lodash'
import ResizeSensor from './base/resize-sensor.vue'
import showShopping from './base/showShopping.vue'
import auxilAgent from './WebchatConAuxilAgent.vue'
import CustomerInformation from './webchat-right/customer-Information/CustomerInformation.vue'
import business from '@/components/public-modules/cust-tab-content/business/businessWebchat/indexWebchat'
import webchatQuickReply from './webchatQuickReply.vue'
import webchatQuickReplyOld from './webchatQuickReplyOld.vue'
import guide from '@/components/public-modules/cust-tab-content/guide/index.vue'
import bus from '@/store/eventBus'
import {LazyRender} from '@/mixins/LazyRender'
import editTab from './webchat-right/customer-Information/dialog/editTab'
import md5 from 'md5'

function updateCurrentWebchatList (store, sid, currentCustomer) {
  store.dispatch('updateCurrentWebchatListCustomer', {sid: sid, customer: currentCustomer})
}

// todo 渲染函数改写
const SizeSync = {
  // template: '<div><slot></slot><resize-sensor @resize="()=>{debugger}"></resize-sensor></div>',
  render: function (createElement) {
    return createElement(this.tag, [this.$slots.default, createElement('resize-sensor', {on: {resize: this.resize}})])
  },
  props: {
    tag: {
      type: String,
      default: 'div'
    },
    size: Object
  },
  components: {
    ResizeSensor
  },
  methods: {
    resize (event) {
      console.log(event)
      this.$emit('update:size', event)
    }
  }
}

export default {
  name: 'WebchatConChatInfo',
  mixins: [LazyRender],
  components: {
    SizeSync,
    ResizeSensor,
    showShopping,
    auxilAgent,
    CustomerInformation,
    business,
    webchatQuickReply,
    webchatQuickReplyOld,
    guide,
    editTab
  },
  data () {
    return {
      timestamp: '',
      size: {},
      offsetIndex: 0,
      activeName: 0,
      cardchangeRandom: 0,
      busId: '',
      toolBarValue: '',
      businessReload: 0,
      tabUrls: [],
      token: '',
      firstIn: 'none',
      toggleLayoutOpen: false,
      isBusiness: false,
      tabs: [],
      quickReplyView: 'listView'
    }
  },
  inject: {
    tabsList: { default: [] }
  },
  props: {
    customer: {
      type: Object,
      default: function () {
        return {}
      }
    },
    currentBusinessObj: Object,
    webchatData: Object,
    chatInfo: Object,
    sendChatMsg: Object
  },
  computed: {
    offsetX () {
      var offsetX = 0
      for (let index = 0; index < this.offsetIndex; index++) {
        var tab = this.tabs[index]
        if (tab && tab.size && tab.size.width) {
          offsetX += tab.size.width + 1
        }
      }
      return offsetX
    },
    totalTabsWidth () {
      var totalTabsWidth = 0
      for (let index = 0; index < this.tabs.length; index++) {
        var tab = this.tabs[index]
        if (tab && tab.size && tab.size.width) {
          totalTabsWidth += tab.size.width + 1
        }
      }
      return totalTabsWidth
    },
    tabswrapperWidth () {
      return this.needOffset ? this.size.width - 75 : this.size.width - 30
    },
    maxOffsetIndex () {
      var offsetX = 0
      var maxOffsetIndex = 0
      for (let index = 0; index < this.tabs.length; index++) {
        maxOffsetIndex = index
        var tab = this.tabs[index]
        if (tab && tab.size && tab.size.width) {
          offsetX += tab.size.width + 1
        }
        if (offsetX + this.tabswrapperWidth > this.totalTabsWidth) {
          break
        }
      }
      return maxOffsetIndex
    },
    needOffset () {
      return this.totalTabsWidth > this.size.width - 29
    },
    path () {
      return this.$route.path.split('/')
    },
    type () {
      return this.path[2] || ''
    },
    tabType () {
      return this.path[3] || ''
    },
    sessionId () {
      return this.path[4] || ''
    },
    custType () {
      let currCustomer = null
      if (this.type === 'webchat') {
        if (this.tabType === 'webchat_todo' || this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_queue') {
          currCustomer = this.$store.state.webchat.current[this.tabType].currentCustomer
        }
      }
      let noCustomer = isEmpty(currCustomer)
      return noCustomer ? 'unk' : 'one'
    }
  },
  activated () {
    let available = this.tabs.filter((item) => {
      return this.showTabs(item.tabName) === true
    }, this)
    if (available[0].tabName) {
      if (available[0].editable) {
        this.activeName = available[0]._id
      } else {
        this.activeName = available[0].tabName
      }
    } else {
      this.activeName = available[0]._id
    }
    this.addLoad(this.activeName)
  },
  watch: {
    maxOffsetIndex () {
      if (this.offsetIndex > this.maxOffsetIndex) {
        this.offsetIndex = this.maxOffsetIndex
      }
    },
    'webchatData._id' () {
      // 记录左侧卡片切换
      this.cardchangeRandom = Math.random()
      if (this.customer._id && this.activeName === 'business') {
        // 如果当前为工单tab，刷新
        this.busId = ''
        this.businessReload = this.cardchangeRandom
        this.firstIn = 'business'
      }
//       切换卡片的时候更新token值
      this.$store.dispatch('getToken').then((token) => {
        this.token = token
      })
      if (['T00000022274', 'T00000024274', 'T00000000003'].includes(this.$store.state.session.account.account) && this.$store.state.session.account.encryType === 'aes') { // 顺丰定制 && 开启了aes加密
        const timestamp = new Date().getTime()
        this.timestamp = timestamp
      }
    },
    $route () {
      if (this.tabType === 'webchat_todo'){
        if (this.$route.path.split('/').length < 5) {
          this.isBusiness = false
        } else {
          this.isBusiness = true
        }
      }
    }
  },
  methods: {
    showTabs (tabName) {
      if (this.tabType === 'webchat_robot' || this.tabType === 'webchat_all' || this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_queue') {
        // 全部或机器人下 隐藏辅助坐席和快捷回复
        if (tabName === 'auxiliaryAgent' || tabName === 'quickReply') {
          return false
        } else {
          return true
        }
      } else if (this.tabType === 'webchat_todo') {
        // 待处理下，如果是留言或已流转会话， 隐藏辅助坐席和快捷回复
        if (this.webchatData.status === 'changePeer') {
          if (tabName === 'auxiliaryAgent' || tabName === 'quickReply') {
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    openTabUrl (tab) {
      let newUrl = this.newUrl(tab.url, tab.isEncode)
      if (this.$store.state.session.account.tokenCheck && this.token) {
        if (newUrl.indexOf('token')) {
          newUrl = newUrl.replace(/(?![?&])(token)=\w+/gi, 'token=' + (this.token.token || ''))
        }
        if (newUrl.indexOf('tokenId')) {
          newUrl = newUrl.replace(/(?![?&])(tokenId)=([A-Za-z0-9|-]+)/gi, 'tokenId=' + (this.token.tokenId || ''))
        }
      }
      let dragMess = {url: newUrl, name: tab.name, open: true}
      this.$store.commit('SET_DRAGPOP', dragMess)
    },
    updateTabConfig (tabs) {
      let data = {
        chatTab: tabs
      }
      this.$store.dispatch('updateChatTabConfig', data).then((res) => {
        if (res.success) {
          this.isdialog = false
          this.tabs = tabs
        }
      })
    },
    handleEditTab () {
      window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-右侧工具栏设置'])
      this.$refs.editTabIndex.open()
    },
    newUrl (url, isEncode) {
      let routes = this.$route.path.split('/')
      let tabType = routes[3]
      let _id = routes[4]
      if (routes[2] !== 'webchat' || !_id) {
        // 切换到其他模块或者是没有到详情的页面的时候，不传参（vepower tab对接，切换到别的模块的时候，赋值了一个不全的地址，切换回来即使地址正确，对接方也取不到正确的地址）
        return ''
      }
      let message = 'tabType=webchat'
      let customer = {}
      let chatSession = {}
      if (tabType === 'webchat_todo') {
        chatSession = this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId] || {}
      } else if (tabType === 'webchat_all' || tabType === 'webchat_robot' || tabType === 'webchat_laterProcess' || tabType === 'webchat_queue') {
        chatSession = this.$store.state.webchat.current[this.tabType].currentSession || {}
      }
      if (chatSession) {
        customer = chatSession.currentCustomer || {}
      }
      let diaplayName = this.$store.state.session.user.displayName || ''
      let exten = this.$store.state.session.user.exten || ''
      if (customer._id) {
        let phone = ''
        let email = ''
        let weixin = ''
        if (customer.phone && customer.phone.length > 0) {
          for (let i = 0; i < customer.phone.length; i++) {
            phone += customer.phone[i].tel + ','
          }
          phone = phone.substr(0, phone.lastIndexOf(','))
        }
        if (customer.email && customer.email.length > 0) {
          for (let i = 0; i < customer.email.length; i++) {
            email += customer.email[i].email + ','
          }
          email = email.substr(0, email.lastIndexOf(','))
        }
        if (customer.weixin && customer.weixin.length > 0) {
          for (let i = 0; i < customer.weixin.length; i++) {
            weixin += customer.weixin[i].num + ','
          }
          weixin = weixin.substr(0, weixin.lastIndexOf(','))
        }
        let name = customer.name ? customer.name : ''
        let custTmpls = this.$getCache('custTmpls')
        let status = customer.status ? custTmpls[0].status[customer.status] : ''
        let title = customer.title ? customer.title : ''
        let province = ''
        let city = ''
        if (customer.city && customer.province) {
          let list = {}
          let options = this.$getCache('options')
          for (let ind in options) {
            if (options[ind].accountId === 'system' && options[ind].name === '省市县') {
              list = options[ind].options
            }
          }
          for (let i = 0; i < list.length; i++) {
            if (list[i].key === customer.province) {
              let optionsNew = list[i].options
              for (let j = 0; j < optionsNew.length; j++) {
                if (optionsNew[j].key === customer.city) {
                  city = optionsNew[j].name
                }
              }
              province = list[i].name
            }
          }
        }
        let address = customer.address ? customer.address : ''
        let note = customer.note ? customer.note : ''
        let web = customer.web ? customer.web : ''
        let age = customer.age ? customer.age : ''
        let birth = customer.birth ? customer.birth : ''
        if (city && province) {
          let list = {}
          let that = this
          this.$store.dispatch('getCache', {type: 'options'}).then(() => {
            let newOptions = that.$getCache('options')
            for (let ind in newOptions) {
              if (newOptions[ind].accountId === 'system' && newOptions[ind].name === '省市县') {
                list = newOptions[ind].options
              }
            }
            for (let i = 0; i < list.length; i++) {
              if (list[i].key === province) {
                for (let j = 0; j < list[i].options.length; j++) {
                  if ((list[i].options[j]).key === city) {
                    city = list[i].options[j].name
                  }
                }
                province = list[i].name
              }
            }
          })
        }
        if (custTmpls && custTmpls.length > 0 && custTmpls[0].template_type !== 'company') {
          let sex = ''
          if (customer.sex) {
            if (customer.sex === '0') {
              sex = this.$t('public.male')
            } else if (customer.sex === '1') {
              sex = this.$t('public.famel')
            }
          }
          message = (message ? message + '&' : '') + 'name=' + name + '&status=' + status + '&title=' + title + '&phone=' + phone + '&email=' + email +
            '&weixin=' + weixin + '&province=' + province + '&city=' + city + '&address=' + address +
            '&note=' + note + '&sex=' + sex + '&age=' + age + '&birth=' + birth + '&displayName=' + diaplayName + '&exten=' + exten + '&sessionId=' + _id
        } else {
          message = (message ? message + '&' : '') + 'name=' + name + '&status=' + status + '&title=' + title + '&phone=' + phone + '&email=' + email +
            '&weixin=' + weixin + '&province=' + province + '&city=' + city + '&address=' + address +
            '&note=' + note + '&web=' + web + '&displayName=' + diaplayName + '&exten=' + exten + '&sessionId=' + _id
        }
        if (chatSession.sid) {
          message += this.getTabParam(chatSession.sid, chatSession.platform, chatSession.sourceName)
        }
      } else {
        if (chatSession.sid) {
          message += this.getTabParam(chatSession.sid, chatSession.platform, chatSession.sourceName)
        }
        message += '&displayName=' + diaplayName + '&exten=' + exten + '&sessionId=' + _id
      }
      if (url && (url.indexOf('power.7moor.com') > -1 || url.indexOf('power-') > -1)) {
        if (this.$store.state.session.sessionId && window.sessionStorage.getItem('loginToken')) {
          message += '&sessionId=' + this.$store.state.session.sessionId + '&loginToken=' + window.sessionStorage.getItem('loginToken')
        }
      }
      message += '&accountId=' + this.$store.state.session.account.account
      if (this.$store.state.session.account.tokenCheck) {
        if (this.token && this.token.token) {
          if (message) {
            message += '&token=' + this.token.token + '&tokenId=' + this.token.tokenId
          } else {
            message = 'token=' + this.token.token + '&tokenId=' + this.token.tokenId
          }
        }
      }
      if (chatSession.otherParams && chatSession.otherParams.customField) {
        if (['T00000022274', 'T00000024274', 'T00000000003'].includes(this.$store.state.session.account.account)) { // 顺丰定制
         Object.keys(chatSession.otherParams.customField).forEach((key) => {
            message += `&${key}=${chatSession.otherParams.customField[key]}`  // 把访客端的数据对象拆分后传递到tab对接 
         })
        } else {
          let customField = JSON.stringify(chatSession.otherParams.customField)
          message += '&customField=' + customField // 客户传给访客端的otherParams回传给tab对接
        }
      }
      if (chatSession.platform) {
        message += '&platform=' + chatSession.platform
      }
      if (['T00000022274', 'T00000024274', 'T00000000003'].includes(this.$store.state.session.account.account)) { // 顺丰定制
        message += `&timestamp=${this.timestamp}`
        const token = 'a4e5ef7c-3bae-4ed8-b1bc-66766fe379ff' // 顺丰提供的固定的sign
        const sign = md5(token + this.timestamp)
        message += `&sign=${sign}`
      }
      if (message.indexOf('#') !== -1) {
        message = message.replace(/#/g, '%23')
      }
      var parpmUrl = ''
      if (message && url && url.indexOf('?') === -1) {
        parpmUrl = url + '?' + message
      } else if (message) {
        parpmUrl = url + '&' + message
      } else {
        parpmUrl = url
      }
      if (isEncode) {
        parpmUrl = encodeURI(parpmUrl)
      }
      return parpmUrl.replace('http://', '//').replace('${customerId}', customer ? customer._id : '')
    },
    getTabParam (sid, platform, sourceName) {
      let tempArr = sid.match(/([^@])+/g) || [] // 哒哒定制只传id不拼其他
      let length = tempArr.length
      let clientUserId = sid
      if (length > 1 && (platform === 'pc' || platform === 'wap' || platform === 'sdk')) {
        let index = platform === 'sdk' ? length - 2 : 0 // pc和wap取第一个sdk取倒数第二个
        clientUserId = tempArr[index]
      }
      return '&qimoClientId=' + sid + '&qimoClientName=' + sourceName + '&clientUserId=' + clientUserId
    },
    businessEvent (eventData) {
      let data = eventData.data
      this.busId = data._id
      if (eventData.event !== 'changeBusinessMaster') {
        this.$store.dispatch('getBusinessDetailById', {_id: this.busId})
      }
      //刷新左侧菜单栏数量统计
      this.$store.commit('business/REFRESH_MENUBAR',Math.random())
    },
    handleTab (tab) {
      if (tab.tabName === 'quickReply') {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-快捷回复tab'])
      }
      if (tab.tabName === 'auxiliaryAgent') {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-辅助座席tab'])
      }
      if (tab.tabName === 'business') {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-建立工单tab'])
      }
      this.addLoad(tab.tabName)
      if (tab.type === 'feature') {
        this.activeName = tab.tabName
        if (this.toggleLayoutOpen) {
          this.$emit('toggleExpandLayout', false)
          this.toggleLayoutOpen = false
        }
      } else {
        this.activeName = tab._id
        this.tabUrls.forEach((taburl) => {
          if (taburl._id === tab._id) {
            taburl.click = true
          }
        })
        this.$emit('toggleExpandLayout', true)
        this.toggleLayoutOpen = true
      }
      if (tab.tabName === 'business') {
        this.busId = ''
        this.firstIn = 'business'
        this.businessReload = this.cardchangeRandom
      }
    },
    handleToggleLayout () {
      this.toggleLayoutOpen = !this.toggleLayoutOpen
      this.$emit('toggleExpandLayout', this.toggleLayoutOpen)
    },
    handlePrevBtnCLick () {
      (this.offsetIndex) && this.offsetIndex--
    },
    handleNextBtnCLick () {
      (this.offsetIndex <= this.maxOffsetIndex) && this.offsetIndex++
    },
    resize (event) {
      this.size = event
    },

    addCustomer (val) {
      delete val.data
      // 写自己添加完客户后相关逻辑
    },
    mergeCustomer (val) {
      let data = {
        customerId: val._id,
        callId: this.$route.params.id,
        custName: val.name,
        customer: val.custInfo,
        submenu: this.tabType,
        sessionId: this.$route.path.split('/')[4]
      }
      return this.$store.dispatch('locationCustomer', data).then(val2 => {
        this.isDailog = false
        this.$message({
          type: 'success',
          message: this.$t('customer.succMerge')
        })
        let sid = null
        if (this.tabType === 'webchat_todo') {
          sid = this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId].sid || ''
        } else {
          sid = this.$store.state.webchat.current[this.tabType].currentSession.sid || ''
        }
        updateCurrentWebchatList(this.$store, sid, val.custInfo)
      })
    },
    getMessageFromChild (data) {
      if (data.data.showCardInfoMsg === '1') {
        bus.$emit('iframeSendCardInfo', data.data)
      }
      if (data.data.showEcCardInfoMsg === '1') {
        bus.$emit('sendShopMsg', data.data)
      }
      if (data.data.showEcOrderInfoMsg === '1') {
        bus.$emit('sendOrderInfoFun', data.data)
      }
    },
    clickIframeFun (data) {
      let isMatched = false
      for (let i = 0; i < this.tabUrls.length; i++) {
        if (data.focusIframe && data.focusIframe === this.tabUrls[i].name) {
          this.tabUrls[i].click = true
          this.activeName = this.tabUrls[i]._id
          this.addLoad(this.activeName)
          isMatched = true
          return
        } else {
          isMatched = false
        }
      }
      if (!isMatched && data.url) {
        try {
          let url = data.url
          let http = /^http:\/\/.*/i.test(url);
          let https = /^https:\/\/.*/i.test(url);
          if (!http && !https) {
            url = 'http://' + url;
          }
          window.open(url, '_blank')
        }
        catch {
          this.$message.error(this.$t('webchat.urlError'))
        }
      }
    }
  },
  beforeMount () {
    let p1 = this.$store.dispatch('getCache', {type: 'tabUrlAddress'})
    let p2 = this.$store.dispatch('getChatTabConfig', {})
    let p3 = this.$store.dispatch('getCache', {type: 'channelGlobalSet'})
    Promise.all([p1, p2, p3]).then((resp) => {
      if (this.$store.state.session.account.tokenCheck) {
        this.$store.dispatch('getToken').then((token) => {
          this.token = token
        })
      }
      let tabUrl = resp[0] // 缓存
      if (tabUrl.length > 0) {
        this.tabUrls = tabUrl
      }
      let chatTab = resp[1] // 接口
      if (chatTab.length > 0) {
        // 新建工单变工单
        chatTab.forEach(item=>{
          if(item.tabName === 'business') {
            item.name = 'business.Business'
          }
        })
        this.tabUrls.forEach((tab) => {
          let a = chatTab.find(chat => tab._id === chat._id)
          if (!a) {
            chatTab.push(tab)
          } else {
            let index = chatTab.findIndex(chat => tab._id === chat._id)
            chatTab[index] = tab
          }
        })
        this.tabs = chatTab
      } else {
        this.tabs = this.tabs.concat(tabUrl)
      }
      this.tabs.forEach((url, index) => {
        if ((url.url || 'businesses' in url) && 'show' in url) {
          this.tabUrls.push(url)
        }
      })
      for (let index = this.tabs.length - 1; index >= 0; index--) {
        let url = this.tabs[index]
        if ('show' in url && !url.show) {
          this.tabs.splice(index, 1)
        }
        if (!url.type) {
          // 无type说明为对接url
          let b = this.tabUrls.find(chat => url._id === chat._id)
          if (!b) {
            // 说明对接url中不存在，已被删除
            this.tabs.splice(index, 1)
          }
        }
      }
      this.tabUrls.forEach((tab) => {
        tab.click = false
        let index = this.tabs.findIndex((a) => {
          return !tab.type && tab._id === a._id
        })
        if (index === 0) {
          tab.click = true
        }
      })
      let available = this.tabs.filter((item) => {
        return this.showTabs(item.tabName) === true
      }, this)
      if (available[0].tabName) {
        if (available[0].editable) {
          this.activeName = available[0]._id
        } else {
          this.activeName = available[0].tabName
        }
      } else {
        this.activeName = available[0]._id
      }
      this.addLoad(this.activeName)
      if (this.activeName === 'business') {
        // 第一个tab为工单时，加载工单模块
        this.firstIn = 'business'
      }
      if (resp[2]) {
        this.quickReplyView = resp[2].quickReply ? resp[2].quickReply : 'listView'
      }
    })
    if (window.addEventListener) {
      window.addEventListener('message', this.getMessageFromChild)
    } else {
      window.attachEvent('onmessage', this.getMessageFromChild)
    }
  },
  mounted () {
    bus.$on('fastSearchWebchatContent', (data) => {
      this.activeName = 'auxiliaryAgent'
      this.addLoad(this.activeName)
    })
    bus.$on('openWebchatKm', () => {
      this.activeName = 'auxiliaryAgent'
      this.addLoad(this.activeName)
    })
    bus.$on('jumpIframeFun', (data) => {
      this.clickIframeFun(data)
    })
  },
  beforeDestroy () {
    window.removeEventListener('message', this.getMessageFromChild)
    bus.$off('fastSearchWebchatContent')
    bus.$off('openWebchatKm')
    bus.$off('jumpIframeFun')
  }
}
</script>
<style lang="stylus">
  .webchat_chat_info
    .el-col.el-col-24.full-add ,.el-col.el-col-24.full-del
      position absolute
      top -2px
      margin-left -6px
    .el-col.el-col-24.full-del
      top 2px
</style>
<style lang="stylus" scoped>
@import '../../../assets/common.styl'
.webchat_chat_info
  .tabsBar
    height 40px
    background $c-back
    line-height 40px
    width 9999px
    button, .tabswrapper
      float left
      height 100%
      border-right: 1px solid #D9D9D9 !important
      text-align center
    .tabswrapper
      overflow hidden
      width 100px
      border-right: 1px solid #D9D9D9
    button
      border: none;
      background: transparent
      border-bottom 1px solid #D9D9D9
      padding 0
      color $c-border2
      cursor pointer
    button:active
      background rgba(0,0,0,0.05)
    button.prev, button.next
      width 22px
      color $cf-level4
    button.config
      border-right: none !important;
      width 28px
      color $cf-level4
    .tabs
      list-style none
      padding 0
      margin 0
      width 9999px
      height 100%;
      .tab
        position relative
        float left
        font-size 12px
        padding 0 13px
        border-right: 1px solid #D9D9D9
        cursor pointer
        color #333333
        border-bottom 1px solid #D9D9D9
        height 39px
        font-weight bold
      .tab.active
        background $cf-white
        color $c-main
        border-bottom 1px solid $cf-white
  .tabPanelsScroll
    overflow-y auto
  .tabPanels
    position relative
    height: calc(100vh - 92px)
    .toggleIcon
      background $cf-white
      position: absolute;
      width: 24px;
      height: 50px;
      top: 0;
      margin: auto;
      bottom: 0;
      left: 0;
      border: 1px solid $c-border1;
      font-size: 16px;
      line-height: 50px;
      text-align: center;
      color: $c-border1;
      cursor: pointer;
      z-index: 12;
      box-shadow: 0 0 5px 0px;
      border-bottom-right-radius: 8px;
      border-top-right-radius: 8px;
    .no-customer
      height: 224px;
      position: relative;
      .main
        color $cf-gray1
        font-size 14px
      .sub
        color $cf-gray3
        font-size 12px
        padding 2px 0 10px

</style>
